package com.audiobo.recorder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;

// Referenced classes of package com.audiobo.recorder:
//            AppletController, AudioUploaderDelegate

class AudioUploader implements Runnable {

  private File uploadFile;
  private String uploadUrl;
  private String uploadField;
  private boolean slowUpload;
  AudioUploaderDelegate _flddelegate;
  private Thread uploaderThread;
  private String prefix;
  private String username;
  private String password;
  private String metadata;

  AudioUploader() {
    slowUpload = false;
    prefix = "";
    username = null;
    password = null;
    metadata = null;
  }

  public void setPrefix(String s) {
    prefix = s;
  }

  public String getPrefix() {
    return prefix;
  }

  public void setUsername(String s) {
    username = s;
  }

  public void setSlowUpload(boolean flag) {
    slowUpload = flag;
  }

  public void setPassword(String s) {
    password = s;
  }

  public void setMetadata(String s) {
    metadata = s;
  }

  public void setDelegate(AudioUploaderDelegate audiouploaderdelegate) {
    _flddelegate = audiouploaderdelegate;
  }

  public boolean start(String s, String s1) {
    System.out.println((new StringBuilder()).append("Upload file ")
        .append(AppletController.audioFilePath).toString());
    uploadFile = new File(AppletController.audioFilePath);
    System.out.println((new StringBuilder()).append("Upload to ").append(s)
        .toString());
    uploadUrl = s;
    uploadField = s1;
    if (uploadFile.exists()) {
      uploaderThread = new Thread(this, "UploaderThread");
      uploaderThread.start();
      return true;
    }

    System.err.println("File doesn't exists");
    return false;
  }

  public void stop() {
    System.out.println("[Upload thread - stop]");
    if (uploaderThread == null || !uploaderThread.isAlive()) {
      return;
    }
    System.out.println("thread is alive");
    uploaderThread.interrupt();
    try {
      uploaderThread.join();
    } catch (Exception e) {
      // do nothing
    }
    uploaderThread = null;
  }

  public boolean isUploadStarted() {
    return uploaderThread != null && uploaderThread.isAlive();
  }

  public void run() {
    HttpURLConnection httpurlconnection;
    String s;
    String s2;
    HttpURLConnection.setFollowRedirects(false);
    httpurlconnection = null;
    s = null;
    if (username != null && password != null) {
      String s1 = (new StringBuilder()).append(username).append(":")
          .append(password).toString();
      // s = (new BASE64Encoder()).encode(s1.getBytes());
      s = s1;
    }
    try {
      s2 = (new StringBuilder()).append(prefix).append(uploadFile.getName())
          .toString();
      httpurlconnection = (HttpURLConnection) (new URL(uploadUrl))
          .openConnection();
      if (s != null) {
        httpurlconnection.setDoInput(true);
        httpurlconnection.setRequestProperty("Authorization",
            (new StringBuilder()).append("Basic ").append(s).toString());
        httpurlconnection.connect();
        httpurlconnection.disconnect();
      }
      httpurlconnection.setRequestMethod("POST");
      String s3 = "boundary220394209402349823";
      String s4 = (new StringBuilder()).append("\r\n--").append(s3)
          .append("--\r\n").toString();
      httpurlconnection.setRequestProperty("Content-Type",
          (new StringBuilder()).append("multipart/form-data; boundary=")
              .append(s3).toString());
      httpurlconnection.setRequestProperty("Accept", "application/json");
      httpurlconnection.setDoOutput(true);
      String s5 = (new StringBuilder()).append("--").append(s3).append("\r\n")
          .append("Content-Disposition: form-data; name=\"_method\"\r\n\r\n")
          .append("put").append("\r\n").toString();
      String s6 = (new StringBuilder()).append("--").append(s3).append("\r\n")
          .append("Content-Disposition: form-data; name=\"")
          .append(uploadField).append("\"; filename=\"").append(s2)
          .append("\"\r\n")
          .append("Content-Type: application/octet-stream\r\n")
          .append("Content-Transfer-Encoding: binary\r\n").toString();
      long l1 = uploadFile.length() + (long) s4.length();
      String s7 = (new StringBuilder()).append("Content-length: ").append(l1)
          .append("\r\n").toString();
      String s8 = (new StringBuilder()).append(s6).append(s7).append("\r\n")
          .toString();
      String s9 = (new StringBuilder()).append(s5).append(s8).toString();
      long l2 = (long) s9.length() + l1;
      httpurlconnection.setRequestProperty("Content-length",
          (new StringBuilder()).append("").append(l2).toString());
      httpurlconnection.setFixedLengthStreamingMode((int) l2);
      httpurlconnection.connect();
      DataOutputStream dataoutputstream = new DataOutputStream(
          httpurlconnection.getOutputStream());
      dataoutputstream.writeBytes(s9);
      dataoutputstream.flush();
      _flddelegate.uploadProgressWithValue(0.0F);
      int i = 0;
      boolean flag = false;
      byte abyte0[] = new byte[1024];
      BufferedInputStream bufferedinputstream = new BufferedInputStream(
          new FileInputStream(uploadFile));
      l1 = uploadFile.length();
      do {
        int j;
        if ((j = bufferedinputstream.read(abyte0)) == -1) {
          break;
        }
        if (!Thread.currentThread().isInterrupted())
          ;
        dataoutputstream.write(abyte0, 0, j);
        dataoutputstream.flush();
        i += j;
        _flddelegate.uploadProgressWithValue((float) i / (float) l1);
        if (slowUpload) {
          try {
            System.out.println("stop for a while");
            Thread.currentThread();
            Thread.sleep(10L);
          } catch (InterruptedException interruptedexception) {
            System.out.println(interruptedexception);
          }
        }
      } while (true);

      dataoutputstream.writeBytes(s4);
      dataoutputstream.flush();
      dataoutputstream.close();
      BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(
          httpurlconnection.getInputStream()));

      String s10;
      while ((s10 = bufferedreader.readLine()) != null) {
        final String l = s10;
        AccessController.doPrivileged(new PrivilegedAction() {

          public Object run() {
            System.out.println((new StringBuilder()).append("response: ")
                .append(l).toString());
            return null;
          }
        });
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    try {
      int k = httpurlconnection.getResponseCode();
      String s11 = httpurlconnection.getResponseMessage();
      System.out.println((new StringBuilder())
          .append("conn.getResponseCode(): ").append(k).toString());
      System.out.println((new StringBuilder())
          .append("conn.getResponseMessage(): ").append(s11).toString());
    } catch (IOException ioexception) {
      System.out.println(ioexception.getMessage());
    }
    if (httpurlconnection != null) {
      httpurlconnection.disconnect();
    }
    _flddelegate.uploadFinished();

    if (httpurlconnection != null) {
      httpurlconnection.disconnect();
    }
    _flddelegate.uploadFinished();

    if (httpurlconnection != null) {
      httpurlconnection.disconnect();
    }
    _flddelegate.uploadFinished();
  }
}
